package com.oa.srms.apps.dao.goods.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.srms.apps.constants.IDEDStates;
import com.oa.srms.apps.dao.goods.IGoodCategoryDao;
import com.oa.srms.apps.entity.goods.GoodCategoryValue;

public class GoodCategoryDaoImpl extends HibernateDaoSupport implements
		IGoodCategoryDao {
	@Autowired
	List<GoodCategoryValue> list;

	@Override
	public int addGoodCategory(GoodCategoryValue goodCategoryValue)
			throws Exception {
		if (goodCategoryValue != null) {
			this.getHibernateTemplate().save(goodCategoryValue);
			return goodCategoryValue.getCategoryId();
		}
		return 0;
	}

	@Override
	public boolean editGoodCategory(GoodCategoryValue goodCategoryValue)
			throws Exception {
		if (goodCategoryValue != null) {
			try {
				this.getHibernateTemplate().update(goodCategoryValue);
			} catch (Exception e) {
				return true;
			}
		}
		return false;
	}

	@Override
	public GoodCategoryValue quaryByCategoryId(
			GoodCategoryValue goodCategoryValue) throws Exception {
		if (goodCategoryValue != null) {
			return (GoodCategoryValue) this.getHibernateTemplate().get(
					GoodCategoryValue.class, goodCategoryValue.getCategoryId());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<GoodCategoryValue> quaryGoodCategoryValue(
			final Integer states) throws Exception {
		String hqlStr = "FROM GoodCategoryValue gcv WHERE 1=1";
		if (states != null) {
			hqlStr += " AND gcv.states = ?";
		}
		hqlStr += " AND gcv.states <> ?";
		final String hql = hqlStr;
		list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				int index = -1;
				if (states != null) {
					query.setInteger(++index, states);
				}
				query.setInteger(++index, IDEDStates.DELETE);
				list = query.list();
				return list;
			}
		});
		return list;
	}

}
